<template>
  <div class="app-container">

    <el-form :model="insureProfit" ref="insureProfit" size="medium" :inline="true" v-show="showSearch"
             label-width="75px">
      <!--      <span>统计日期：{{selectionDate}}</span>-->
      <el-form-item label="统计月份" prop="searchMonth">
        <el-date-picker
          v-model="searchMonth"
          type="month"
          value-format="yyyy-MM"
          placeholder="选择月份"
          :disabled="monthDisabled"
          @change="handleChangeMonth"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="统计季度" prop="searchQuarter">
        <template>
          <div>
            <quarter-picker
              format="yyyy年q季度"
              value-format="yyyy-MM"
              placeholder="选择季度"
              v-model="searchQuarter"
              :disabled="quarterDisabled"
              :disabled-date="disabledQuarter"
              @change="handleChangeQuarter"/>
          </div>
        </template>
      </el-form-item>

      <el-form-item label="统计年份" prop="searchYear">
        <el-date-picker
          v-model="searchYear"
          type="year"
          value-format="yyyy"
          placeholder="选择年份"
          :disabled="yearDisabled"
          @change="handleChangeYear"
        >
        </el-date-picker>
      </el-form-item>

    </el-form>

    <el-divider></el-divider>

    <!--    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch" label-width="68px">-->

    <!--      <el-form-item label="供应商" prop="supplierId">-->
    <!--        <el-select v-model="queryParams.supplierId" placeholder="请选择供应商" @change="handleChangeSupplierId" clearable-->
    <!--                   filterable>-->
    <!--          <el-option-->
    <!--            v-for="item in allSupplierList"-->
    <!--            :key="item.id"-->
    <!--            :label="item.name"-->
    <!--            :value="item.id"-->
    <!--          />-->
    <!--        </el-select>-->
    <!--      </el-form-item>-->

    <!--      <el-form-item>-->
    <!--        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>-->
    <!--        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>-->
    <!--      </el-form-item>-->
    <!--    </el-form>-->

    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['statementDetail:statementDetail:add']"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['statementDetail:statementDetail:edit']"
              >修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['statementDetail:statementDetail:remove']"
              >删除</el-button>
            </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['reportGeneration:insureProfit:export']"
        >导出报表
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="insureProfitList" @selection-change="handleSelectionChange" show-summary
              :summary-method="getSummaries"
              stripe>
      <el-table-column  width="80" align="center"/>
      <el-table-column label="序号" type="index" align="center" width="50"/>
      <el-table-column label="投保服务费(元)" align="center" prop="charge"/>
      <el-table-column label="投保成本(元)" align="center" prop="cost"/>
      <el-table-column label="附加税(元)" align="center" prop="additionalTax"/>
      <el-table-column label="服务费利润(元)" align="center" prop="profit"/>
      <el-table-column label="结算周期" align="center" prop="cycle"/>
      <el-table-column label=" " align="center" width="50">
        <template slot-scope="scope">
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-edit"-->
          <!--            @click="handleUpdate(scope.row)"-->
          <!--            v-hasPermi="['statementDetail:statementDetail:edit']"-->
          <!--          >修改-->
          <!--          </el-button>-->
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-delete"-->
          <!--            @click="handleDelete(scope.row)"-->
          <!--            v-hasPermi="['statementDetail:statementDetail:remove']"-->
          <!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改投保服务费利润对话框 -->
    <!--    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>-->
    <!--      <el-form ref="form" :model="form" :rules="rules" label-width="80px">-->
    <!--        &lt;!&ndash;        <el-form-item label="结算单表id" prop="statementId">&ndash;&gt;-->
    <!--        &lt;!&ndash;          <el-input v-model="form.statementId" placeholder="请输入结算单表id" />&ndash;&gt;-->
    <!--        &lt;!&ndash;        </el-form-item>&ndash;&gt;-->
    <!--        <el-form-item label="员工方案表id" prop="employeeProjectId" v-if="false">-->
    <!--          <el-input v-model="form.employeeProjectId" placeholder="请输入员工方案表id"/>-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="备注" prop="employeeProjectRemark">-->
    <!--          <el-input v-model="form.employeeProjectRemark" type="textarea" placeholder="请输入内容" :autosize="{ minRows: 4, maxRows: 9}"  maxlength="255" show-word-limit/>-->
    <!--        </el-form-item>-->
    <!--      </el-form>-->
    <!--      <div slot="footer" class="dialog-footer">-->
    <!--        <el-button type="primary" @click="submitForm">确 定</el-button>-->
    <!--        <el-button @click="cancel">取 消</el-button>-->
    <!--      </div>-->
    <!--    </el-dialog>-->
  </div>
</template>

<script>

import QuarterPicker from '@/components/quarter-picker'
import {listInsureProfit} from "@/api/report_generation/reportgeneration";

export default {
  name: "InsureProfit",
  dicts: ['insurance_policy_property', 'sys_user_sex',],
  components: {
    QuarterPicker
  },

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 投保服务费利润表格数据
      insureProfitList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        supplierId: null,
        supplierName: null,
        signMainName: null,
        companyName: null,
        companyNameSecond: null,
        businessType: null,
        supervisorCharge: null,
        salesman: null,
        mobilePhone: null,
        queryTime: null,
        queryType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      //投保服务费利润
      insureProfit: {},
      //所选日期
      selectionDate: "",
      //按月
      searchMonth: "",
      //按季度
      searchQuarter: "",
      //按年
      searchYear: "",

      //年选择器禁用
      yearDisabled: false,
      //月选择器禁用
      monthDisabled: false,
      //季度选择器禁用
      quarterDisabled: false,


      // 禁用日期/季度示例，只允许选择本年度本季度（不含）之前的季度
      disabledQuarter: time => {
        const now = new Date()
        return time.getFullYear() > now.getFullYear() || time.getFullYear() === now.getFullYear() && parseInt(time.getMonth() / 3) >= parseInt(now.getMonth() / 3)
      }

    };
  },
  created() {
    this.initQueryTimeType();
    this.getList();
  },
  methods: {
    /** 初始化 查询日期 查询日期类型 */
    initQueryTimeType() {
      if (this.queryParams.queryTime == null) {
        const now = new Date();
        const year = now.getFullYear();
        // const month = ('0' + (now.getMonth() + 1)).slice(-2);
        // const date = year + "-" + month;
        // this.queryParams.queryTime = date;
        // this.queryParams.queryType = "1";
        // this.searchMonth = date;
        // this.selectionDate = year + "年" + month + "月";
        this.queryParams.queryTime = year;
        this.queryParams.queryType = "3";
        this.searchYear = year.toString();
        this.selectionDate = year + "年";
      }
    },

    /** 查询投保服务费利润列表 */
    getList() {
      this.loading = true;
      listInsureProfit(this.queryParams).then(response => {
        this.insureProfitList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //获取结算单 投保成本信息
    // getStatementInsureCostInfo(statementId) {
    //   getInsureCostInfo(statementId).then(response => {
    //     this.statementInsureCostInfo = response.data
    //   });
    // },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        statementId: null,
        employeeId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        employeeProjectRemark: null,
        employeeProjectId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.employeeProjectId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加投保服务费利润";
    },
    /** 修改按钮操作 */
    // handleUpdate(row) {
    //   this.reset();
    //   const id = row.employeeProjectId || this.ids
    //   getStatementDetail(id).then(response => {
    //     this.form = response.data;
    //     this.open = true;
    //     this.title = "修改投保服务费利润";
    //   });
    // },
    /** 提交按钮 */
    // submitForm() {
    //   this.$refs["form"].validate(valid => {
    //     if (valid) {
    //       if (this.form.id != null) {
    //         updateStatementDetail(this.form).then(response => {
    //           this.$modal.msgSuccess("修改成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       } else {
    //         addStatementDetail(this.form).then(response => {
    //           this.$modal.msgSuccess("新增成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       }
    //     }
    //   });
    // },
    /** 删除按钮操作 */
    // handleDelete(row) {
    //   const ids = row.id || this.ids;
    //   this.$modal.confirm('是否确认删除投保服务费利润编号为"' + ids + '"的数据项？').then(function () {
    //     return delStatementDetail(ids);
    //   }).then(() => {
    //     this.getList();
    //     this.$modal.msgSuccess("删除成功");
    //   }).catch(() => {
    //   });
    // },

    // handleChangeSupplierId() {
    //   if (this.queryParams.supplierId) {
    //     const id = this.queryParams.supplierId
    //     let name = "";
    //     this.allSupplierList.forEach(item => {
    //       if (id === item.id) {
    //         name = item.name;
    //       }
    //     })
    //     this.queryParams.supplierName = name;
    //   } else {
    //     this.queryParams.supplierName = null;
    //   }
    // },

    /** 导出按钮操作 */
    handleExport() {
      let excelName = this.selectionDate + "投保服务费利润";
      this.download('reportGeneration/insureProfit/export', {
        ...this.queryParams
      }, excelName + `_${new Date().getTime()}.xlsx`)
    },

    //月、季度、年选择器变化之处理
    handleChangeQuarter(date) {
      if (date != null) {
        this.queryParams.queryTime = this.searchQuarter;
        this.queryParams.queryType = "2"
        this.getList();
        const strings = this.searchQuarter.split("-");
        const string = strings[0];
        const string1 = strings[1];
        var string2 = "";
        if (string1 === "01") {
          string2 = "第1季度";
        } else if (string1 === "04") {
          string2 = "第2季度";
        } else if (string1 === "07") {
          string2 = "第3季度";
        } else {
          string2 = "第4季度";
        }
        this.selectionDate = string + "年" + string2;
        this.searchYear = null;
        this.searchMonth = null;
      }
    },
    handleChangeMonth(date) {
      if (date != null) {
        this.queryParams.queryTime = this.searchMonth;
        this.queryParams.queryType = "1"
        this.getList();
        const strings = this.searchMonth.split("-");
        const string = strings[0];
        const string1 = strings[1];
        this.selectionDate = string + "年" + string1 + "月";
        this.searchQuarter = null;
        this.searchYear = null;
      }
    },
    handleChangeYear(date) {
      if (date != null) {
        this.queryParams.queryTime = this.searchYear;
        this.queryParams.queryType = "3"
        this.getList();
        this.selectionDate = this.searchYear + "年";
        this.searchQuarter = null;
        this.searchMonth = null;
      }
    },

    getSummaries(param) {
      // console.log(param)
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = '合计';
          return;
        }
        if (index === 10) {
          sums[index] = '';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] = Math.round(parseFloat(sums[index]) * 100)/100
          sums[index] += ' 元';
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },

  }
};
</script>
